package org.bunny.vehicle.service.driver;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.bunny.vehicle.entity.Journey;
import org.bunny.vehicle.entity.Vehicle;
import org.bunny.vehicle.service.BaseService;
import org.bunny.vehicle.util.Const;
import org.bunny.vehicle.util.JSON;
import org.directwebremoting.annotations.RemoteProxy;
import org.directwebremoting.spring.SpringCreator;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

@RemoteProxy(creator = SpringCreator.class)
@Service
public class DriverWorkService extends BaseService {

	public Page<Journey> getJourneyList(String json) {
		JSONObject obj = JSON.parseObject(json);

		int page = JSON.getInteger(obj, "page");

		return journeyRepository.findByDriverAndVerifyStatus(getUser(), Journey.VERIFY_PASSED,
				new PageRequest(page, Const.PAGE_SIZE, Sort.Direction.DESC, "id"));
	}

	public Page<Vehicle> getVehicleList(String json) {
		JSONObject obj = JSON.parseObject(json);

		int page = JSON.getInteger(obj, "page");

		Pageable pageable = new PageRequest(0, Integer.MAX_VALUE, Sort.Direction.DESC, "id");
		List<Journey> journeyList = journeyRepository.findByDriverAndVerifyStatus(getUser(),
				Journey.VERIFY_PASSED, pageable).getContent();
		Set<Vehicle> vehicleSet = new HashSet<Vehicle>();
		for (Journey journey : journeyList) {
			Vehicle vehicle = journey.getVehicle();
			if (null != vehicle) {
				vehicleSet.add(vehicle);
			}
		}
		List<Vehicle> vehicleList = new ArrayList<Vehicle>(Const.PAGE_SIZE);
		int begin = page * Const.PAGE_SIZE;
		int end = begin + Const.PAGE_SIZE;
		int i = 0;
		for (Vehicle vehicle : vehicleSet) {
			if (begin <= i && end > i) {
				vehicleList.add(vehicle);
			}
			++i;
		}

		return new PageImpl<Vehicle>(vehicleList, pageable, vehicleSet.size());
	}

}
